﻿using AFanDa.BLL.BaseService;
using AFanDa.Dto.Base;
using AFanDa.Dto.Reponse;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace AFanDa.BLL.BLLService
{
    public class AdminService : ResultService
    {

        private readonly BaseAdminService _adminService = null;

        public AdminService()
        {
            _adminService = new BaseAdminService();
        }

        /// <summary>
        /// 获取所有用户 根据条件s
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ApiResult GetAdmins(Dto.Request.AdminRequestDto dto)
        {

            Expression<Func<Dto.EF.Admin, bool>> where = d => d.AName.Contains(dto.key);

            if (dto.status != -1)
            {
                where = d => d.AName.Contains(dto.key) && d.status == dto.status;
            }
            var iq = _adminService.QueryAll(out int total, dto.page, dto.limit, o => o.Aid, true, where);

            List<AdminResponseDto> list = new List<AdminResponseDto>();
            iq.ToList().ForEach(d =>
            {
                list.Add(new AdminResponseDto
                {
                    Aid = d.Aid,
                    Name = d.AName,
                    CreateTime = Convert.ToDateTime(d.ACreateTime).ToString("yyyy-MM-dd"),
                    Account = d.Account,
                });
            });


            return GetResult(ApiCode.ok, data: new
            {
                total,
                data = list
            });



        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ApiResult AddAdmin(Dto.Request.AdminRequestDto dto)
        {

            string key = Common.Config.GetKey("LoginKey");
            string pwd = Common.EncryptUtil.LoginMd5(dto.Password, key);
            _adminService.Add(new Dto.EF.Admin()
            {
                Aid = Common.Config.GUID(),
                Account = dto.Account,
                Password = pwd,
                status = 0,
                AName = dto.name,
                ACreateTime = DateTime.Now
            });

            var result = _adminService.SaveChange();

            if (result > 0)
            {
                return new ApiResult()
                {
                    code = ApiCode.ok,
                    message = "添加成功"
                };
            }

            return new ApiResult()
            {
                code = ApiCode.fail,
                message = "添加失败"
            };
        }
    }
}
